package net.color4me.app.farmere.action;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.color4me.app.farmere.entity.FarmUser;
import net.color4me.app.farmere.server.EMF;
import net.color4me.app.farmere.server.FarmerClient;

@SuppressWarnings("serial")
public class MockLoginServlet extends HttpServlet {
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("UTF-8");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		FarmerClient famer = new FarmerClient();

		FarmUser user = famer.login(username, password);
		if (user.getLink().startsWith("http:") && !user.getCookieStr().equals("")) {
			
			EntityManager em = EMF.get().createEntityManager();
			try {
				em.persist(user);
			} finally {
				em.close();
			}
			req.setAttribute("msg", user.getUser() + "已经登陆成功了~~");

		} else {
			req.setAttribute("msg", "用户名密码错了吧"); 
		}
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("text/html; charset=UTF-8");
			req.getRequestDispatcher("/jsp/loginresult.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
}
